package com.cxl.server.impl;

import com.cxl.entity.User;
import com.cxl.repository.UserRepository;
import com.cxl.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author: 20971
 * @time: 2022/3/10 10:41
 * @description:
 */
@Service
public class UserServerImpl implements UserServer {

    @Autowired
    private UserRepository userRepository;

    /*列表 + 查询  +分页 + 排序*/
    @Override
    public Page<User> queryList(User user, Integer pageNum, Integer pageSize) {

        //封装查询条件
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                ArrayList<Predicate> predicates = new ArrayList<>();
                if (user.getUsername() != null && user.getUsername() != "") {
                    Predicate username = criteriaBuilder.like(root.get("username"), '%' + user.getUsername() + '%');
                    predicates.add(username);
                }
                if (user.getStartDate() != null) {
                    Predicate predicate = criteriaBuilder.greaterThanOrEqualTo(root.get("birthday").as(Date.class), user.getStartDate());
                    predicates.add(predicate);
                }
                if (user.getEndDate() != null) {
                    Predicate predicate = criteriaBuilder.lessThanOrEqualTo(root.get("birthday"), user.getEndDate());
                    predicates.add(predicate);
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        PageRequest of = PageRequest.of(0, 3, Sort.Direction.ASC, "birthday");
        Page<User> page = userRepository.findAll(specification, of);
        return page;
    }
}
